//
//  UDRegViewController.swift
//  Chatter
//
//  Created by David on 16/7/13.
//  Copyright © 2016年 David. All rights reserved.
//  注册


import UIKit

@objc protocol FCRegDelegate {
    @objc optional func didFinishReg()
}

enum FCTriBoxFormAction {
    case register
    case forgetPassword
    case bindAccount
}

class UDRegViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {
    
    var tableView:UITableView!
    var navigationBar:UINavigationBar!
    
    var emailTextField:UDTextField!
    var passwordTextField:UDTextField!
    var verifyTextField:UDTextField!
    //private var verifyImg:UIButton!
    var registerBtn:UIButton!
    var msg:UILabel!
    
    var spinnerBG:UIView!
    
//    var delegate: UDLoginRegDelegate?
    
    
    //register compare with login
    
    var passwordConfirmTextField:UDTextField!
    var getSmsCodeBtn: UIButton!
    
    var sendSmsCountDown = 60
    
    // DEL: private var forgetPswBtn:UIButton!
    // DEL: requireVerify:Bool
    // DEL: func checkNeedVerify()
    
    /*
     @objc private func refreshVerifyImg(){
     NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.GET_VERIFY)")!), queue: NSOperationQueue(), completionHandler: { (resp:NSURLResponse?, returnData:NSData?, err:NSError?) in
     if err == nil{
     if let data = returnData{
     dispatch_async(dispatch_get_main_queue(), {
     self.verifyImg.setImage(UIImage(data: data), forState: .Normal)
     self.spinnerBG.alpha = 0
     })
     }
     }
     })
     }
     */
    var formAction: FCTriBoxFormAction = .register
    convenience init(action: FCTriBoxFormAction){
        self.init()
        formAction = action
    }
    
    var unameToBind:String?
    
    convenience init(bindUsername: String?){
        self.init()
        formAction = .bindAccount
        unameToBind = bindUsername
    }
    
    override var preferredStatusBarStyle : UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        navigationController?.modalTransitionStyle = .crossDissolve
        
        
        tableView = UITableView(frame: CGRect(x: 0, y: 44, width: self.view.frame.width, height: self.view.frame.height - 44), style: .plain)
        tableView.keyboardDismissMode = .onDrag
        tableView.allowsSelection = false
//        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 32))
        self.view.addSubview(tableView)
        
        msg = UILabel(frame: CGRect(x: 0, y: 40, width: self.view.frame.width, height: 24))
        msg.textAlignment = .center
        msg.font = UIFont.systemFont(ofSize: 12)
        
        msg.textColor = UIColor.brown
        msg.backgroundColor = UIColor.orange
        msg.alpha = 0
        msg.center.y = 52
        view.addSubview(msg)
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .black
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        navigationBar.tintColor = UIColor.white
        
        var navTitle = "注册"
        
        switch formAction {
        case .register:
            navTitle = "注册"
            break
        case .forgetPassword:
            navTitle = "找回密码"
            break
        default:
            break
        }
        
        let navItem = UINavigationItem(title: navTitle)
        navigationBar.pushItem(navItem, animated: true)
        
        if formAction == .bindAccount {
            navItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(UDRegViewController.goBack))
        }else{
            navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(UDRegViewController.dismissAll))
        }
        
//        navItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: .plain, target: self, action: #selector(UDRegViewController.gotoLogin))
        
        emailTextField = UDTextField(frame: CGRect(x: 16, y: 0, width: self.view.frame.width - 32, height: 44))
        emailTextField.boderWidth = 0
        emailTextField.placeholder = "11位手机号"
        emailTextField.keyboardType = .numberPad
        emailTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        emailTextField.iconView.image = #imageLiteral(resourceName: "phone")
        emailTextField.text = unameToBind
        
        verifyTextField = UDTextField(frame: CGRect(x: 16, y: 0, width: self.view.frame.width - 128, height: 44))
        verifyTextField.boderWidth = 0
        verifyTextField.textFieldType = .verify
        verifyTextField.placeholder = "手机验证码"
        verifyTextField.keyboardType = .numberPad
        verifyTextField.tabIndex = 1
        verifyTextField.returnKeyType = .next
        verifyTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        verifyTextField.iconView.image = #imageLiteral(resourceName: "verify")
        
        getSmsCodeBtn = UIButton(frame: CGRect(x: self.view.frame.width - 108, y: 8, width: 96, height: 28))
        getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
        getSmsCodeBtn.setTitleColor(themeColor2, for: UIControlState())
        getSmsCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        getSmsCodeBtn.layer.cornerRadius = 4
        getSmsCodeBtn.layer.borderColor = themeColor2.cgColor
        getSmsCodeBtn.layer.borderWidth = 1
//        getSmsCodeBtn.backgroundColor = Fatcat.THEME_COLOR
        getSmsCodeBtn.addTarget(self, action: #selector(UDRegViewController.getSmsCode(_:)), for: .touchUpInside)
        
        
        
        passwordTextField = UDTextField(frame: CGRect(x: 16, y: 0, width: self.view.frame.width - 32, height: 44))
        passwordTextField.boderWidth = 0
        passwordTextField.textFieldType = .password
        passwordTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        passwordTextField.placeholder = "设置密码"
        passwordTextField.tabIndex = 2
        passwordTextField.iconView.image = #imageLiteral(resourceName: "password")
        
        passwordConfirmTextField = UDTextField(frame: CGRect(x: 16, y: 0, width: self.view.frame.width - 32, height: 44))
        passwordConfirmTextField.boderWidth = 0
        passwordConfirmTextField.textFieldType = .password
        passwordConfirmTextField.tabIndex = 3
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.nextInput(_:)), for: .editingDidEndOnExit)
        passwordConfirmTextField.placeholder = "确认密码"
        passwordConfirmTextField.addTarget(self, action: #selector(UDRegViewController.scrollUpTextField(_:)), for: .editingDidBegin)
        
        /*
         verifyImg = UIButton(frame: CGRect(x: self.view.frame.width - 91.2, y: 24 + emailTextField.frame.height + 8 + passwordTextField.frame.height + 8 + passwordConfirmTextField.frame.height + 8 + verifyTextField.frame.height + 8, width: 83.2, height: 32))
         verifyImg.backgroundColor = UIColor.grayColor()
         verifyImg.contentMode = .ScaleToFill
         verifyImg.addTarget(self, action: #selector(UDRegViewController.refreshVerifyImg), forControlEvents: .TouchUpInside)
         */
        
        registerBtn = UIButton(frame: CGRect(x: 0, y: 16, width: 48, height: 48))
//        registerBtn.setTitle("注册", for: UIControlState())
        registerBtn.center.x = view.center.x
        
        registerBtn.layer.borderColor = themeColor2.cgColor
        registerBtn.layer.borderWidth = 1
        registerBtn.layer.cornerRadius = 24
        
//        registerBtn.setImage(#imageLiteral(resourceName: "arrow_black"), for: .normal)
        
//        registerBtn.backgroundColor = Fatcat.THEME_COLOR
//        registerBtn.setTitleColor(UIColor.white, for: UIControlState())
        registerBtn.addTarget(self, action: #selector(UDRegViewController.register), for: .touchUpInside)
        registerBtn.adjustsImageWhenDisabled = true
        registerBtn.adjustsImageWhenHighlighted = true
        
        let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 64))
        let arrowIcon = UIImageView(frame: CGRect(x: 0, y: 0, width: 28, height: 28))
        arrowIcon.center = CGPoint(x: 24, y: 24)
        arrowIcon.image = #imageLiteral(resourceName: "arrow_black")
        registerBtn.addSubview(arrowIcon)
//        footer.addSubview(registerBtn)
        tableView.tableFooterView = footer
        
        spinnerBG = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinnerBG.center = view.center
        spinnerBG.backgroundColor = UIColor(white: 0, alpha: 0.75)
        spinnerBG.layer.cornerRadius = 5
        view.addSubview(spinnerBG)
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        spinner.center = CGPoint(x: 25, y: 25)
        spinner.activityIndicatorViewStyle = .white
        spinner.startAnimating()
        spinnerBG.addSubview(spinner)
        spinnerBG.alpha = 0
        //refreshVerifyImg()
        
        //        self.scrollView.addSubview(self.emailTextField)
        //        self.scrollView.addSubview(self.passwordTextField)
        //        self.scrollView.addSubview(self.passwordConfirmTextField)
        //        self.scrollView.addSubview(self.verifyTextField)
        //        self.scrollView.addSubview(self.verifyImg)
        //        self.scrollView.addSubview(self.registerBtn)
        //        self.scrollView.addSubview(self.msg)
        self.emailTextField.becomeFirstResponder()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UDRegViewController.resendSmsTimer), userInfo: nil, repeats: true)
        
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 4
        }
        return 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == 3{
            return 96
        }
        return 48
    }

    /*
     func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
     if section == 0{
     return 32
     }
     if section == 1{
     return 1
     }
     return 0
     }
     func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     if section == 0{
     return msg
     }
     return nil
     }
     */
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "row")
        if indexPath.section == 0{
            switch indexPath.row {
            case 0:
                cell.addSubview(emailTextField)
                break
            case 2:
                cell.addSubview(verifyTextField)
                cell.addSubview(getSmsCodeBtn)
                break
            case 1:
                cell.addSubview(passwordTextField)
                break
            case 3:
//                cell.addSubview(passwordConfirmTextField)
                cell.addSubview(registerBtn)
                
                if formAction == .register {
                    let infoLabel = UILabel(frame: CGRect(x: 16, y: 72, width: 150, height: 20))
                    infoLabel.center.x = view.center.x - 45
                    infoLabel.textAlignment = .center
                    infoLabel.text = "注册后表示同意喵印的"
                    infoLabel.font = UIFont.systemFont(ofSize: 14)
                    infoLabel.textColor = UIColor.lightGray
                    cell.addSubview(infoLabel)
                    
                    let userAgreementBtn = UIButton(frame: CGRect(x: infoLabel.frame.origin.x + infoLabel.frame.width, y: infoLabel.frame.origin.y, width: 90, height: 20))
                    userAgreementBtn.setTitle("《使用协议》", for: .normal)
                    userAgreementBtn.setTitleColor(themeColor1, for: .normal)
                    userAgreementBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                    cell.addSubview(userAgreementBtn)
                    userAgreementBtn.addTarget(self, action: #selector(UDRegViewController.goUserAgreement), for: .touchUpInside)
                }
                
                break
            default:
                break
            }
        }else if indexPath.section == 1 && indexPath.row == 0 {
            cell.addSubview(registerBtn)
        }
        return cell
    }
    
    
    func nextInput(_ sender: UDTextField){
        switch sender.tabIndex {
        case 0:
            verifyTextField.becomeFirstResponder()
            break
        case 1:
            register()
            break
        case 2:
//            passwordConfirmTextField.becomeFirstResponder()
            passwordTextField.becomeFirstResponder()
            
            break
        case 3:
            register()
            break
        default:
            break
        }
    }
    
    func goUserAgreement(){
        present(UserAgreementViewController(), animated: true, completion: nil)
    }
    
    func getSmsCode(_ sender: UIButton){
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            return
        }
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return
        }else{
            
            if NSString(string: emailTextField.text!).substring(to: 1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return
                }
            }
        }
        setErrorMsg("")
        emailTextField.resignFirstResponder()
        
//        let alert = UIAlertController(title: "用户注册获取验证码接口未正确指定", message: nil, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
//        self.present(alert, animated: true, completion: nil)
        //http://114.215.105.95/print/index.php?m=admin&c=user&a=userSms
        //tyep=1(发送注册验证码) type=2(发送修改密码验证码)  username=13726204184&phone=13726204184
        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userSms")!)
        resq.httpMethod = "POST"
        
        var verifyType = 1
        
        if formAction == .forgetPassword {
            verifyType = 2
        }
        getSmsCodeBtn.isEnabled = false
        resq.httpBody = "type=\(verifyType)&username=\(emailTextField.text!)&phone=\(emailTextField.text!)".data(using: .utf8)
        URLSession.shared.dataTask(with: resq, completionHandler: { (reData:Data?, resp:URLResponse?, err:Error?) in
            var failed = true
            if err == nil {
                if let data = reData {
                    print(String(data: data, encoding: .utf8) ?? "data error")
                    let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
                    if jsonObj?.object(forKey: "code") != nil {
                        let reCode = jsonObj?.object(forKey: "code") as! Int
                        if reCode == 200 {
                            failed = false
                        }else if reCode == 202 {
                            failed = false
                            DispatchQueue.main.async(execute: {
                                
                                
                                let alert = UIAlertController(title: "用户已注册", message: nil, preferredStyle: .alert)
                                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                                self.present(alert, animated: true, completion: nil)
                            })
                        }
                    }
                }
            }
            if failed {
                DispatchQueue.main.async(execute: {
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)
                    
                })
            }
        }) .resume()
        
    }
    
    @objc fileprivate func register(){
        if checkInput() {
            postRequest()
        }
    }
    
    
    fileprivate func checkInput() ->Bool{
//        tableView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        if emailTextField.text == ""{
            setErrorMsg("请输入手机号码")
            emailTextField.becomeFirstResponder()
            
            return false
        }
        
        // MARK: 打开这段代码检查邮箱地址
        /*
         if emailTextField.text!.componentsSeparatedByString("@").count != 2{
         setErrorMsg("邮箱地址不正确")
         emailTextField.becomeFirstResponder()
         return false
         }
         */
        if emailTextField.text?.characters.count != 11{
            setErrorMsg("手机号码不正确")
            emailTextField.becomeFirstResponder()
            return false
        }else{
            if NSString(string: emailTextField.text!).substring(to: 1) != "1"{
                setErrorMsg("手机号码不正确")
                emailTextField.becomeFirstResponder()
                return false
            }else{
                if Int64(emailTextField.text!) == nil {
                    setErrorMsg("手机号码不正确")
                    emailTextField.becomeFirstResponder()
                    return false
                }
            }
        }
        
        
        
        if passwordTextField.text == ""{
            setErrorMsg("请输入密码")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        // MARK: 打开这段代码检查密码长度
        
        if (passwordTextField.text?.characters.count)! < 6{
            setErrorMsg("密码长度不足")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
        if (passwordTextField.text?.characters.count)! > 16{
            setErrorMsg("密码长度太长")
            passwordTextField.becomeFirstResponder()
            return false
        }
        
//        if passwordTextField.text != passwordConfirmTextField.text{
//            setErrorMsg("两次密码不一致")
//            passwordConfirmTextField.becomeFirstResponder()
//            return false
//        }
        
        if verifyTextField.text == ""{
            setErrorMsg("请输入验证码")
            verifyTextField.becomeFirstResponder()
            return false
        }else{
            if Int64(verifyTextField.text!) == nil {
                setErrorMsg("输入的验证码不合法")
                verifyTextField.becomeFirstResponder()
                return false
            }
        }
        setErrorMsg("")
        
        return true
    }
    
    fileprivate func postingStatus(_ status: Bool){
        
        emailTextField.isEnabled = !status
        passwordTextField.isEnabled = !status
        passwordConfirmTextField.isEnabled = !status
        verifyTextField.isEnabled = !status
        //verifyImg.enabled = !status
        registerBtn.isEnabled = !status
        if status{
            spinnerBG.alpha = 1
        }else{
            spinnerBG.alpha = 0
        }
    }
    
    fileprivate func postRequest(){
//        postingStatus(true)
        
        
        
//        FCUserReg.shared.startRegister()
//        FCUserReg.shared.username = emailTextField.text!
//        FCUserReg.shared.password = passwordTextField.text!
//        FCUserReg.shared.code = verifyTextField.text!
//        navigationController?.pushViewController(SchoolViewController(), animated: true)
//        navigationController?.pushViewController(SchoolViewController(regData: "username=\(emailTextField.text!)&password=\(passwordTextField.text!)&code=\(verifyTextField.text!)"), animated: true)
        postingStatus(true)
        var actionPost = "userRegister"
        if formAction == .forgetPassword {
            actionPost = "userEditPwd"
        }
        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=\(actionPost)")!)
        resq.httpMethod = "POST"
        resq.httpBody = "username=\(emailTextField.text!)&password=\(passwordTextField.text!)&code=\(verifyTextField.text!)".data(using: .utf8)
        
        URLSession.shared.dataTask(with: resq) { (data:Data?, resp:URLResponse?, err:Error?) in
            DispatchQueue.main.async {
                self.postingStatus(false)
            }
            do{
                if err != nil{
                    throw err!
                }
                if data == nil{
                    throw NSError(domain: "RegisterApiReturnDataNil", code: 9, userInfo: nil)
                }
//                print(String(data: data!, encoding: .utf8) ?? "data not string")
                DispatchQueue.main.async {
                    self.handleResult(data!)
                }
                
            }catch let ex{
                print(ex)
//                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
//                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.setErrorMsg("请求出错")
                }
            }
        }.resume()
    }
    
    fileprivate func handleResult(_ res: Data){
        print(String(data: res, encoding: .utf8) ?? "data error")
        
        let jsonObj = try? JSONSerialization.jsonObject(with: res, options: .allowFragments) as! NSDictionary
        if jsonObj != nil{
            if jsonObj?.object(forKey: "code") != nil{
                let reCode = jsonObj?.object(forKey: "code") as! Int
                if reCode == 200 {
                    // MARK: 注册完成  保存登陆信息
                    
                    if formAction == .forgetPassword{
                        let alert = UIAlertController(title: "密码已修改", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in
                            self.dismiss(animated: true, completion: nil)
                        }))
                        present(alert, animated: true, completion: nil)
                    }else{
                        UserDefaults.standard.set(true, forKey: orderListRefreshRequireKey)
                        FCUserReg.shared.startRegister()
                        FCUserReg.shared.username = emailTextField.text
                        
                        let cookies = HTTPCookieStorage.shared.cookies!
                        let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                        UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                        UserDefaults.standard.set(self.emailTextField.text!, forKey: loginUserDefaultKeyName)
                        
                        URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo")!) { (data:Data?, resp:URLResponse?, err:Error?) in
                            do{
                                if err != nil{
                                    throw err!
                                }
                                
                                print(String(data: data!, encoding: .utf8) ?? "data nil")
                                
                                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                                
                                let nickName = jsonData?.object(forKey: "nickname") as? String
                                let face = jsonData?.object(forKey: "face") as? String
                                
                                if !ChangyanSDK.isLogin(){
                                    ChangyanSDK.loginSSO(self.emailTextField.text!, userName: nickName ?? "", profileUrl: "\(apiBaseDomainName)?m=admin&c=user&a=userinfo", imgUrl: face ?? "", complete: { (code, msg) in
                                        if code == CYSuccess {
                                            print("changyan login success:")
                                            print(msg ?? "no respond")
                                        }
                                    })
                                }
                                
                            }catch let ex{
                                print(ex)
                            }
                            }.resume()
                        
                        navigationController?.pushViewController(SchoolViewController(), animated: true)
                    }
                    
//                    switch formAction {
//                    case .register:
//                        UserDefaults.standard.set(emailTextField.text!, forKey: loginUserDefaultKeyName)
                        
//                        let cookies = HTTPCookieStorage.shared.cookies!
//                        let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
//
//                        UserDefaults.standard.set(cookiesData, forKey: "cookies")
//                        UserDefaults.standard.synchronize()
//                        dismiss(animated: false, completion: nil)
                        
//                        delegate?.doubleDismissRegView?()
//                        break
//                    case .forgetPassword:
//                        
//                        break
//                    default:
//                        break
//                    }
                    
                    
                }else{
                    setErrorMsg(jsonObj?.object(forKey: "message") as! String)
                    postingStatus(false)
                }
                
                return
            }
        }
        setErrorMsg("json error")
        postingStatus(false)
        
    }
    
    fileprivate func setErrorMsg(_ message: String){
        if message != ""{
            if msg.alpha == 0{
                msg.text = message
                self.msg.alpha = 1
                UIView.animate(withDuration: 0.3, delay: 0, options: .curveLinear, animations: {
                    
                    self.msg.center.y = 76
                }, completion: { (finished) in
                    UIView.animate(withDuration: 0.3, delay: 3, options: .curveLinear, animations: {
                        self.msg.center.y = 52
                    }, completion: { (finished1) in
                        self.msg.alpha = 0
                    })
                })
            }
            
        }
    }
    
    
    @objc fileprivate func gotoLogin(){
        dismiss(animated: true, completion: nil)
        
    }
    func dismissAll(){
        dismiss(animated: true, completion: nil)
//        delegate?.doubleDismissRegView?()
    }
    
    func goBack(){
        _ = navigationController?.popViewController(animated: true)
    }
    
    func resendSmsTimer(){
        if !getSmsCodeBtn.isEnabled {
            if sendSmsCountDown < 0{
                getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
                getSmsCodeBtn.isEnabled = true
                sendSmsCountDown = 60
                return
            }
            getSmsCodeBtn.setTitle("\(sendSmsCountDown)s", for: UIControlState())
            sendSmsCountDown -= 1
        }
        
    }
    
    func scrollUpTextField(_ sender:UITextField){
        print(tableView.contentOffset.y)
//        if tableView.contentOffset.y <= 0 {
//            tableView.setContentOffset(CGPoint(x: 0, y: 64), animated: true)
//        }
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
